<template>
	<view class="container">
		<view class="status_bar" style="height: var(--status-bar-height); width: 100%;"></view>

		<nav-bar
			fixed
			:title="title"
			:cover="doneLen > 0"
			@click-left="goBack"
		/>

		<view class="submit-box" v-if="isSubmit">
			<view class="bg-top"></view>
			<view class="box-content">
				<text>已提交</text>
				<text>您的考核已提交，可在管理员阅卷后查看分数</text>
				<text>将在 {{ second }}s 后，自动跳转回理论测验页面</text>
				<button class="btn primary" @tap="goList">直接跳转</button>
			</view>
		</view>

		<view class="content" v-else>
			<view class="timer" v-if="isTimeLimit">
				剩余时间：{{ formatSeconds(remainTime) }}
			</view>

			<view class="card">
				<view class="question-type">
					<text>{{ curQuesTypeName }}</text>
					<view class="info">
						<text>{{ `【${curQues.questionScore}分】` }}</text>
						<text>{{ curQuesIdx }}</text>
						<text>/</text>
						<text>{{ curQuesTypeArr.length }}</text>
					</view>
				</view>
				<view class="divider"></view>

				<view class="question">{{ curQues.titleContent }}</view>
				<uni-data-checkbox
					mode="button"
					v-if="curQues.questionType < 4"
					v-model="result[curQues.idx]"
					:multiple="curQues.questionType === 2"
					:localdata="curQues.items"
					:map="{ text: 'content2', value: 'prefix' }"
				/>
				<view class="options" v-else-if="curQues.questionType === 4">
					<view v-for="(item, index) in curQues.items" :key="index">
						<text>{{ item.prefix }}.</text>
						<uni-easyinput
							v-model="result[curQues.idx][index]"
							:clearable="false"
							placeholder="请输入"
						/>
					</view>
				</view>
				<view v-else-if="curQues.questionType === 5">
					<uni-easyinput
						type="textarea"
						v-model="result[curQues.idx]"
						:maxlength="1000"
						autoHeight
						placeholder="请输入"
					/>
				</view>
			</view>

			<view class="btns">
				<button
					class="btn primary"
					:disabled="isPrevOne"
					@tap="changeQuestion('prev')"
				>
					上一题
				</button>
				<button
					v-if="!isNextOne"
					class="btn primary"
					@tap="changeQuestion('next')"
				>
					下一题
				</button>
				<button v-else class="btn success" @tap="onSubmit">交卷</button>
			</view>
		</view>

		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog
				type="info"
				cancelText="取消"
				confirmText="确定"
				title="注意"
				:content="dialogContent"
				@confirm="submit"
			/>
		</uni-popup>

		<uni-popup ref="backDialog" type="dialog">
			<uni-popup-dialog
				type="info"
				cancelText="取消"
				confirmText="确定"
				title="注意"
				content="当前信息未保存，离开页面将会放弃所有修改"
				@confirm="back"
			/>
		</uni-popup>
	</view>
</template>

<script setup>
import { toRaw, computed, ref, onUnmounted } from 'vue'
import { onLoad, onBackPress } from '@dcloudio/uni-app'
import { getExamPaperInfo, submitExamPaper } from '@/net/lilunceyan.js'
import { formatSeconds } from '@/utils/fun.js'
import NavBar from '@/components/nav-bar.vue'

onLoad(params => {
	getQuestionData(params.id)
})

const title = ref()
const isTimeLimit = ref(false)
// 倒计时
const remainTime = ref(0)
// 用时
const doTime = ref(0)
// 返回倒计时
const second = ref(5)
// 原数据信息
const questionData = ref([])
// 格式化后数据信息
const questionList = ref({})
// 答题信息
const result = ref([])
// 当前类型
const curTypeIdx = ref(0)
// 当前类型下第几题
const curQuesIdx = ref(1)
const alertDialog = ref()
const backDialog = ref()
const dialogContent = ref()
const isSubmit = ref(false)
// 答题数量
const doneLen = computed(() => {
	const arr = [...result.value]
	const len = arr.filter(item => {
		if (Array.isArray(item)) {
			item =
				item.filter(Boolean).length > 0 && JSON.stringify(item) !== '[]'
		}
		return Boolean(item)
	}).length
	return len
})
// 当前类型名称
const curQuesTypeName = computed(() => {
	const questionTypeArr = ['单选题', '多选题', '判断题', '填空题', '简答题']
	const questionNumArr = ['一', '二', '三', '四', '五', '六']
	return (
		questionNumArr[curTypeIdx.value] +
		'、' +
		questionTypeArr[curQues.value.questionType - 1]
	)
})
// 当前类型下试题列表
const curQuesTypeArr = computed(() => {
	return questionList.value[curTypeIdx.value] || []
})
// 当前试题
const curQues = computed(() => {
	return curQuesTypeArr.value[curQuesIdx.value - 1] || {}
})
const isPrevOne = computed(() => {
	return curQuesIdx.value <= 1 && curTypeIdx.value <= 0
})
const isNextOne = computed(() => {
	return (
		curQuesIdx.value >= curQuesTypeArr.value.length &&
		curTypeIdx.value >= questionList.value.length - 1
	)
})

let timer = null
const countdown = () => {
	timer = setInterval(() => {
		if (remainTime.value <= 0) {
			submit()
		} else {
			++doTime.value
			--remainTime.value
		}
	}, 1000)
}

const getQuestionData = async id => {
	const { data } = await getExamPaperInfo({ id })
	title.value = data.name
	if (data.isTimeLimit == 2) {
		isTimeLimit.value = data.isTimeLimit == 2
		remainTime.value = (data.suggestTime || 5) * 60
		countdown()
	}
	const obj = {}
	let idx = 0
	data.djQuestionList.forEach(item => {
		item.idx = idx++
		if (item.questionType === 4) {
			result.value[item.idx] = item.items.map(v => '')
		}
		item.items = item.items?.map(v => {
			v.content2 = `${v.prefix}. ${v.content}`
			return v
		})
		const { questionType } = item
		if (!obj[questionType]) {
			obj[questionType] = []
		}
		obj[questionType].push(item)
	})
	questionList.value = Object.values(obj)
	questionData.value = { ...data }
}

const changeQuestion = tag => {
	if (tag === 'prev') {
		if (curQuesIdx.value > 1) {
			// 当前类型内循环
			curQuesIdx.value--
		} else {
			if (curTypeIdx.value > 0) {
				// 类型切换 数据重置
				curTypeIdx.value--
				// 定位到新类型内最后一个
				curQuesIdx.value = curQuesTypeArr.value.length
			}
		}
	} else if (tag === 'next') {
		if (curQuesIdx.value < curQuesTypeArr.value.length) {
			// 当前类型内循环
			curQuesIdx.value++
		} else {
			if (curTypeIdx.value < questionList.value.length - 1) {
				// 类型切换 数据重置
				curTypeIdx.value++
				// 定位到新类型内第一个
				curQuesIdx.value = 1
			}
		}
	}
}

const goBack = () => {
	doneLen.value > 0 && backDialog.value.open()
}
const back = () => {
	uni.navigateBack({ delta: 1 })
}

const onSubmit = () => {
	const allLen = result.value.length
	const allDone = allLen > 0 && doneLen.value === allLen
	const txt = allDone ? '试题已答完' : '还有试题未答'
	dialogContent.value = txt + '，确定要交卷吗？'
	alertDialog.value.open()
}

let backTimer = null
const submit = async () => {
	const { examPaperId, djQuestionList } = toRaw(questionData.value)
	const examPaperCustomerSubmits = djQuestionList.map(item => {
		let obj = {}
		if (item.questionType === 4) {
			obj = {
				questionId: item.id,
				gapFill: result.value[item.idx].map((v, i) => {
					return { prefix: i + 1, content: v || '' }
				})
			}
		} else if (item.questionType === 2) {
			obj = {
				questionId: item.id,
				content: result.value[item.idx]?.join()
			}
		} else {
			obj = {
				questionId: item.id,
				content: result.value[item.idx]
			}
		}
		return obj
	})
	timer && clearInterval(timer)
	const params = { examPaperId, examPaperCustomerSubmits }
	isTimeLimit.value && (params.doTime = doTime.value)
	try {
		await submitExamPaper(params)
		isSubmit.value = true
		backTimer = setInterval(() => {
			second.value--
			if (second.value <= 0) {
				clearInterval(backTimer)
				goList()
			}
		}, 1000)
	} catch (e) {
		console.log(e)
	}
}

const goList = () => {
	uni.redirectTo({ url: './index' })
}

onUnmounted(() => {
	timer && clearInterval(timer)
	backTimer && clearInterval(backTimer)
})
</script>

<style lang="scss">
@import '/static/common.scss';
page {
	height: 100%;
}
.container {
	height: 100%;
	display: flex;
	flex-direction: column;
	.submit-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding-top: 510rpx;
		background-color: #fff;
		position: relative;
		.bg-top {
			position: absolute;
			top: 0;
			width: 100%;
			height: 650rpx;
			background-image: url('@/static/dangjian/submit-status.png');
			background-size: 100% 100%;
			background-repeat: no-repeat;
		}
		.box-content {
			display: flex;
			align-items: center;
			flex-direction: column;
			z-index: 2;
			text {
				&:first-child {
					font-size: 44rpx;
					line-height: 60rpx;
					margin-bottom: 10rpx;
					color: #000;
				}
				&:not(:first-child) {
					font-size: 28rpx;
					line-height: 40rpx;
					margin-top: 24rpx;
					color: #333;
				}
			}
			button {
				width: 50%;
				padding: 16rpx 0;
				margin-top: 80rpx;
			}
		}
	}
	.content {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		.timer {
			font-size: 24rpx;
			line-height: 56rpx;
			text-align: center;
			box-shadow: rgba(0, 0, 0, 0.08) 0px 1px 3px 0;
			background-color: #fff;
			color: #e86565;
		}
		.card {
			flex: 1;
			margin-top: 20rpx;
			padding: 24rpx 30rpx;
			overflow: auto;
			background-color: #fff;
			border-top-left-radius: 8rpx;
			border-top-right-radius: 8rpx;
			box-shadow: rgba(0, 0, 0, 0.08) 0px -1px 3px 0;
		}
		.btns {
			padding: 30rpx;
			display: flex;
			background-color: #fff;
			.btn {
				flex: 1;
				line-height: 88rpx;
			}
		}
	}
}
.question-type {
	display: flex;
	justify-content: space-between;
	> text {
		color: #3b95ff;
	}
	.info {
		color: #999;
		text:nth-child(2) {
			color: #3b95ff;
		}
	}
}
.question {
	font-size: 30rpx;
	margin-bottom: 30rpx;
	color: #000;
}
.options > view {
	font-size: 30rpx;
	display: flex;
	align-items: center;
	& + view {
		margin-top: 20rpx;
	}
	text {
		&:first-child {
			margin-right: 20rpx;
		}
		&:last-child {
			flex: 1;
		}
	}
}
:deep(.uni-data-checklist .checklist-group) {
	display: block !important;
	.checklist-box.is--button {
		margin: 0 !important;
		padding: 20rpx !important;
		.checklist-content {
			.checklist-text {
				line-height: 22px;
				font-size: 30rpx;
				margin-left: 20rpx;
			}
		}
		& + .checklist-box.is--button {
			margin-top: 20rpx !important;
		}
	}
}
:deep(.is-input-border) {
	border-radius: 3px;
}
</style>
